import React, { useCallback, useEffect, useState } from "react";
import { Form, Button, Input, Select, Checkbox, Space, DatePicker, message, Popconfirm, Image } from "antd";
import CommonStoreSearchInput from "@/views/components/CommonStoreSearchInput/index";
import { SearchSimpleTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";

import BatchSuffixInput from "@/views/components/BatchSuffixInput";

import { goodsSkuMatch, goodsSpuMatch, getZJFStorePage, supplierMatchOp, changeGoodsSkuMatch } from "./service";
import { renderCityOptions } from '@/utils/utils.jsx';

const cityOptions = renderCityOptions();

const beforeQuerySearch = ({ API_DATA }) => {
	const key = "storeId";
	const value = API_DATA["storeIdCopy1"] || API_DATA["storeIdCopy2"];
	delete API_DATA["storeIdCopy1"];
	delete API_DATA["storeIdCopy2"];
	API_DATA[key] = value;
	return { ...API_DATA, size: API_DATA.pageSize, current: API_DATA.pageNum };
};
const TablePage = props => {
	const { selectedRows, isSkuType, isOrderGoods, isChangeMatch, onDrawerClose } = props;

	// 更换匹配：组装api和入参
	const getChangeMatchApiConfig = (TEXT, record) => {
		const API_DATA = {
			id: selectedRows[0]?.matchedId,
			matchType: 1,
			supplierId: record.storeId,
			supplierName: record.storeName
			// supplierSkuId: record.goodsId,
			// // "supplierSkuImage": "128*68纯棉床笠",
			// supplierSkuName: record.goodsName,
			// supplierSkuPrice: record.vipPrice || record.goodsPrice,
			// supplierSkuSpecs: record.color + ";" + record.size,
			// supplierSpuCode: record.goodsCommonid
		};

		const MATCH_API = changeGoodsSkuMatch;
		return { API_DATA, MATCH_API };
	};
	// 添加匹配：组装api和入参
	const getAddMatchApiConfig = (TEXT, record) => {
        const goodsMatchStoreList = [], orderIdsArr = [];
        selectedRows.forEach(item => {
            goodsMatchStoreList.push({
                storeId: record.storeId,
                storeName: record.storeName,
                sysGoodsId: item.sysGoodsId,
                shopCode: record.shopCode
            })
            orderIdsArr.push(item.orderIds);
        })
		const API_DATA = isOrderGoods
			? {
					goodsMatchStoreList,
					orderIds: orderIdsArr.flat()
				}
			: {
					ids: selectedRows.map(e => (isSkuType ? e.skuId : e.spuId)),
					list: [
						{
							supplierId: record.storeId,
							supplierName: record.storeName
						}
					],
					type: 1 //关联类型 1：供应商 2：供应商商品
				};
		const MATCH_API = isSkuType ? (isOrderGoods ? supplierMatchOp : goodsSkuMatch) : goodsSpuMatch;
		return { API_DATA, MATCH_API };
	};
	const handleCommand = (TEXT, record) => {
		// 根据 isChangeMatch 获取 不同的api 和 data;
		let config, pre;
		if (isChangeMatch) {
			config = getChangeMatchApiConfig(TEXT, record);
			pre = "更换";
		} else {
			config = getAddMatchApiConfig(TEXT, record);
			pre = "";
		}
		const { MATCH_API, API_DATA } = config || {};

		// 执行api
		MATCH_API(API_DATA)
			.then(res => {
				const { success, data, msg } = res;
				if (success) {
					onDrawerClose(selectedRows[0]?.orderIds);
					message.success(msg || pre + "匹配成功");
				} else {
					message.warning(msg || pre + "匹配失败");
				}
			})
			.catch(err => {
				console.error(err);
				message.warning(pre + "匹配接口请求失败");
			});
	};

	const defaultColumns = [
		{
			name: "供应商名称",
			code: "storeName",
			width: 200,
			search: {
				order: 2,
				code: "storeIdCopy1",
				content: () => <CommonStoreSearchInput type="storeName" placeholder="请输入供应商名称" />
			}
		},
		{
			name: "城市",
			code: "siteCityName",
			width: 120,
			search: {
				order: 1,
				code: "cityName",
				content: () => (
					<Select placeholder="城市" options={cityOptions}></Select>
				)
			}
		},
		{
			name: "档口号",
			code: "shopCode",
			width: 200,
			search: {
				order: 3,
				code: "storeIdCopy2",
				content: () => <CommonStoreSearchInput type="shopCode" placeholder="请输入档口号" />
			}
		},
		{
			lock: true,
			code: "action",
			width: 80,
			name: "操作",
			align: "center",
			render(_, record) {
				return (
					<>
						<Popconfirm
							placement="leftTop"
							title="是否确定匹配？"
							onConfirm={() => {
								handleCommand("匹配", record);
							}}
							onCancel={() => {}}
						>
							<Button type="link">匹配</Button>{" "}
						</Popconfirm>
					</>
				);
			},
		}
	];
	const [columns, setColumns] = useState(defaultColumns);
	const tableRequest = getZJFStorePage;
	const tableKey = "SystemGoodsMatchSupplierMatchTable";
	const { searchSimpleTableProps } = useTableConfig({
		className: "scrollbar",
		tableKey,
		rowKey: "id",
		// ///
		columns,
		tableRequest,
		autoFetch: true,
		hasPagination: true,
		hasQuickSearch: false,
		beforeQuerySearch,
		resetSourceData: false,
		hasColsSetting: false,
		hasToggleSearchForm: false,
		columnResize: true,
		searchSpan: 3,
        pageSize: 50
	});
	return <SearchSimpleTable key={tableKey} mounted={false} {...searchSimpleTableProps} />;
};

export default React.memo(TablePage, () => {
	return true;
});
